import { AudioOutlined, CarOutlined, CheckCircleOutlined, CheckCircleTwoTone, CheckOutlined, CopyOutlined, DownloadOutlined, PlusOutlined, SendOutlined, UploadOutlined, UserOutlined } from '@ant-design/icons';
import {
    DrawerForm,
    ModalForm,
    ProCard,
    ProForm,
    ProFormDateRangePicker,
    ProFormInstance,
    ProFormSelect,
    ProFormText,
    ProFormTextArea,
} from '@ant-design/pro-components';
import { Alert, Button, Descriptions, Divider, Space, Spin, Tag, Typography, Upload, message, Image, DescriptionsProps, Card, Row, Col, UploadFile, Tabs } from 'antd';
import { useEffect, useRef, useState } from 'react';
import EnrollMedia from './EnrollMedia';
import EnrollOrganization from './EnrollOrganization';
import { useAccess } from 'umi';
import AddTravelArrangements from './AddTravelArrangements';
import TabelReports from './TabelReports';
import { detailInterview, detailRegistration, registrationInfoInit } from '@/services/api/api-interview-record';
import RegistrationInfo from './RegistrationInfo';
interface DetailsInterviewProps {
    id: string;
    title: string;
    interviewId: string;
    onRefurbish: () => void;
    triggerMode: 'card' | 'title';
    item: InterviewRecordData.PageVo;

}

const DetailsInterview: React.FC<DetailsInterviewProps> = ({ id, title, onRefurbish, interviewId, triggerMode, item }) => {
    const access = useAccess();
    const [drawerVisit, setDrawerVisit] = useState(false);
    const formRef = useRef<ProFormInstance>();
    const [details, setDetailsState] = useState<InterviewRecordData.InterviewDetail>();
    const [modalFormOpen, setModalFormOpenState] = useState<boolean>(false);
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewData, setPreviewData] = useState<{
        id: string;
        name: string;
        mimeType: string;
        url?: string;
    }>();
    const [previewOnlineUrl, setPreviewOnlineUrl] = useState<string>();
    const iframeRef = useRef(null);
    const [previewLoading, setPreviewLoading] = useState(true);
    const [tab, setTab] = useState('media');
    const [planTab, setPlanTab] = useState();
    const [planItems, setPlanItems] = useState();
    const [registrationInfo, setRegistrationInfo] = useState<InterviewRecordData.planList>({} as InterviewRecordData.planList);
    const [detailRegistData, setDetailRegistData] = useState<InterviewRecordData.assignOrganizationList>({} as InterviewRecordData.assignOrganizationList);
    const [reload, setReload] = useState(false)


    //获取报名信息详情
    const getDetailRegistData = async () => {
        const res = await detailRegistration({ recordId: id })
        if (res.code === 0) {
            setDetailRegistData(res.data)
        }
    }

    //获取报名信息
    const getRegistrationInfo = async () => {
        const res = await registrationInfoInit({ recordId: id })
        if (res.code === 0) {
            if (res.data.length > 0) {
                setRegistrationInfo(res.data)
            } else {
                setRegistrationInfo([])
            }
        }
    }

    /**
  * 获取 详情
  * @param key
  */
    const loadSubmitDetails = async () => {
        try {
            const response = await detailInterview({ id });
            if (response.code === 0) {
                setDetailsState(response.data)
                console.log(response.data);
                setPlanTab(response.data?.planList[0].id)
                const plan = response.data?.planList.map((item, index) => {
                    return {
                        key: item.id,
                        tab: "出行安排" + (index + 1)
                    }
                })
                console.log(plan);
                
                setPlanItems(plan)
            }

        } catch (error) { }
    };

    useEffect(() => {
        if (interviewId === id) {
            if (interviewId !== undefined) {
                setDrawerVisit(true);
            }
        }
    }, [])


    return (
        <>
            <DrawerForm
                onVisibleChange={(visible) => {
                    if (visible) {
                        loadSubmitDetails()
                        getDetailRegistData()
                        getRegistrationInfo()
                    } else {
                        onRefurbish()
                    }
                    setDrawerVisit(visible)
                }}
                title={<div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    {/* <span>{title}</span> */}
                    {/* <DetailTravelArrangements detail={details} /> */}
                    <TabelReports id={id} title={title} />
                    <Button type='primary' icon={<UploadOutlined />}>导出word</Button>
                </div>}
                visible={drawerVisit}
                onFinish={async () => {
                    message.success('提交成功');
                    return true;
                }}
                drawerProps={{
                    width: "100%"
                }}
                trigger={
                    triggerMode === 'card' ? (
                        <div
                            style={{
                                paddingLeft: 10,
                                paddingRight: 10,
                                paddingBottom: 10,
                            }}
                        >
                            <Card
                                bordered={false}
                                hoverable
                                style={{
                                    background: 'linear-gradient(#F5FBFF,#fff, #fff)',
                                }}
                            >
                                <Card.Meta
                                    title={
                                        // <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                        <div>
                                            <div
                                                style={{
                                                    whiteSpace: 'nowrap',
                                                    overflow: 'hidden',
                                                    textOverflow: 'ellipsis',
                                                    minWidth: 65,
                                                }}
                                            >
                                                <Tag color={item.status === 0 ? 'error' : 'success'}>{item.status === 0 ? '已结束' : '进行中'}</Tag>
                                                {item.title}
                                            </div>
                                            <div
                                                style={{
                                                    float: 'left',
                                                }}
                                            >

                                            </div>
                                        </div>
                                    }
                                    description={
                                        <>
                                            <Typography.Paragraph ellipsis={true}>
                                                {
                                                    <span
                                                        style={{
                                                            color: '#888A8C',
                                                            fontSize: 15,
                                                        }}
                                                    >
                                                        {item.content}
                                                        {/* <div>
                                                            采访媒体:<Space wrap size={1}>{item.mediaNames.map((item) => {
                                                                return <Tag key={item}> {item}</Tag>;
                                                            })}</Space>
                                                        </div>
                                                        <div>采访对象: {item.assignOrganizationNames.map((item) => {
                                                            return <Tag key={item}> {item}</Tag>;
                                                        })}</div>
                                                        <div>采访地点: {item.address.map((item) => {
                                                            return <Tag key={item}> {item}</Tag>;
                                                        })}</div> */}
                                                        <div>
                                                            采访媒体 :
                                                            <Space wrap size={1} style={{ marginLeft: 5 }}>
                                                                {item.mediaNames.slice(0, 2).map((item) => {
                                                                    return <>
                                                                        <Tag key={item}> {item}</Tag>
                                                                    </>;
                                                                })}
                                                                {Array.isArray(item.mediaNames) && item.mediaNames.length > 2 && <Tag >...</Tag>}
                                                            </Space>
                                                        </div>
                                                        <div>
                                                            采访对象 :
                                                            <Space wrap size={1} style={{ marginLeft: 5 }}>
                                                                {item.assignOrganizationNames.slice(0, 2).map((item) => {
                                                                    return <>
                                                                        <Tag key={item}> {item}</Tag>
                                                                    </>;
                                                                })}
                                                                {Array.isArray(item.assignOrganizationNames) && item.assignOrganizationNames.length > 2 && <Tag >...</Tag>}
                                                            </Space>
                                                        </div>
                                                        {/* <div>
                                                            采访地点 :
                                                            <Space wrap size={1} style={{ marginLeft: 5 }}>
                                                                {item.address.slice(0, 2).map((item) => {
                                                                    return <>
                                                                        <Tag key={item}> {item}</Tag>
                                                                    </>;
                                                                })}
                                                                {Array.isArray(item.address) && item.address.length > 2 && <Tag >...</Tag>}
                                                            </Space>
                                                        </div> */}
                                                    </span>
                                                }
                                            </Typography.Paragraph>
                                            <div
                                                style={{
                                                    marginTop: 5,
                                                    marginRight: 18,
                                                    display: 'flex',
                                                    justifyContent: 'space-between',
                                                    width: '100%'
                                                }}
                                            >
                                                <span
                                                >
                                                    创建时间：
                                                    {item.createdTime}
                                                </span>
                                            </div>
                                        </>
                                    }
                                />
                            </Card>
                            <div
                                style={{
                                    borderRadius: 12,
                                    background: '#FFF',
                                }}
                            ></div>
                        </div>
                    ) : (
                        <a>{title}</a>
                    )
                }
                submitter={{
                    render: (props, defaultDoms) => {
                        return [
                            access.采访要素匹配x管理员 && <AddTravelArrangements
                                onRefurbish={() => { loadSubmitDetails(), getRegistrationInfo() }}
                                // planList={registrationInfo as InterviewRecordData.planList}
                                planList={details?.planList as InterviewRecordData.planList}
                                registrationInfo={registrationInfo}
                                // planList={[]}
                                id={String(details?.id)}
                            />,
                            (access.采访要素匹配x采访媒体 && details?.interviewState === 1) && <EnrollMedia onRefurbish={() => { setReload(!reload), getDetailRegistData() }} id={String(details?.id)} detailRegistData={detailRegistData} />,
                            (access.采访要素匹配x采访对象 && details?.interviewState === 1) && <EnrollOrganization onRefurbish={() => { setReload(!reload), getDetailRegistData() }} id={String(details?.id)} detailRegistData={detailRegistData} />
                        ];
                    },
                }}
            >

                <Spin
                    style={{
                        textAlign: 'center',
                    }}
                    spinning={details === undefined}
                >

                    {details !== undefined && (
                        <>
                            {title ? (
                                <Typography.Title
                                    copyable={{
                                        icon: [
                                            <CopyOutlined
                                                style={{
                                                    fontSize: '16px',
                                                }}
                                                key="copy-icon"
                                            />,
                                            <CheckOutlined
                                                style={{
                                                    fontSize: '16px',
                                                }}
                                                key="copied-icon"
                                            />,
                                        ],
                                    }}
                                    level={3}
                                    style={{ textAlign: 'center' }}
                                >
                                    {title}

                                </Typography.Title>
                            ) : (
                                <Typography.Title level={3} style={{ textAlign: 'center' }}>
                                    暂无标题
                                </Typography.Title>
                            )}
                            <div style={{ display: "flex", justifyContent: 'flex-end', alignItems: 'center' }}>

                                <Descriptions>
                                    <Descriptions.Item label="活动内容">
                                        <div style={{ display: 'flex', fontSize: 15 }}>
                                            <div
                                                dangerouslySetInnerHTML={{
                                                    __html: `${details?.content}`,
                                                }}
                                            />
                                        </div>
                                    </Descriptions.Item>
                                </Descriptions>

                            </div>
                            <Descriptions>
                                {details?.planList && details?.planList.length > 0 && <Descriptions.Item label="报名信息">
                                    <DrawerForm
                                        trigger={<a>点击查看</a>}
                                        title="报名信息"
                                        formRef={formRef}
                                        autoFocusFirstInput
                                        drawerProps={{
                                            maskClosable: true,
                                            destroyOnClose: true,
                                            width: '100%',
                                        }}
                                        visible={modalFormOpen}
                                        onVisibleChange={(visible) => {
                                            if (visible) {
                                                setReload(!reload)
                                            }
                                            setModalFormOpenState(visible)
                                        }}
                                        submitTimeout={2000}
                                        submitter={false}

                                    >
                                        <RegistrationInfo id={details.id} reload={reload} />
                                    </DrawerForm>
                                </Descriptions.Item>}
                            </Descriptions>
                            <Descriptions>
                                <Descriptions.Item label="截止时间">{details?.deadlineTime}</Descriptions.Item>
                            </Descriptions>

                            {/* style={{display:'flex',justifyContent:'flex-end'}} */}

                            {details?.attachments && details?.attachments.length > 0 && (
                                <>
                                    <div
                                        style={{
                                            textAlign: 'right',
                                        }}
                                    >
                                        <Button
                                            type="primary"
                                            key="import"
                                            size="small"
                                            icon={<DownloadOutlined />}
                                            onClick={() => {
                                                details?.attachments.forEach(function (item) {
                                                    window.open(item.content, '_blank');
                                                });
                                            }}
                                        >
                                            全部下载
                                        </Button>
                                    </div>

                                    <Upload
                                        listType="picture"
                                        multiple
                                        fileList={details?.attachments.map((item) => {
                                            return {
                                                uid: item.id,
                                                name: item.name,
                                                url: item.content,
                                                mimeType: item.mimeType,
                                                status: 'done',
                                            };
                                        })}
                                        showUploadList={{
                                            downloadIcon: (
                                                <div style={{ marginLeft: '-100px', padding: '17px 0', marginTop: '-15px' }}>
                                                    <DownloadOutlined
                                                        style={{
                                                            marginRight: '10px',
                                                        }}
                                                    />
                                                    点击下载
                                                </div>
                                            ),
                                            showRemoveIcon: false,
                                            showDownloadIcon: true,
                                        }}
                                        onPreview={async (file: UploadFile) => {
                                            setPreviewData({
                                                id: file.uid,
                                                name: file.name,
                                                mimeType: file.mimeType,
                                                url: file.url,
                                            });
                                            setPreviewOpen(true);
                                        }}
                                    />
                                    <DrawerForm
                                        title={previewData?.name}
                                        drawerProps={{
                                            width: 900,
                                            destroyOnClose: true,
                                        }}
                                        visible={previewOpen}
                                        onVisibleChange={async (visible) => {
                                            if (visible) {
                                                if (
                                                    previewData?.mimeType !== null &&
                                                    previewData?.mimeType?.indexOf('image') > -1
                                                ) {
                                                    //图片预览
                                                } else {
                                                    setPreviewLoading(true);

                                                    // const response = await cuesAttachmentPreview({
                                                    //     id: previewData?.id,
                                                    // });

                                                    // if (response.code === 0) {
                                                    //     setPreviewOnlineUrl(response.data);
                                                    // } else {
                                                    //     message.error('暂时无法预览');
                                                    //     setPreviewLoading(false);
                                                    // }
                                                }
                                            } else {
                                                setPreviewOpen(false);
                                                setPreviewData(undefined);
                                                setPreviewOnlineUrl(undefined);
                                            }
                                        }}
                                        submitter={{
                                            searchConfig: {
                                                submitText: '下载',
                                            },
                                        }}
                                        onFinish={async (values) => {
                                            window.open(previewData?.url, '_blank');
                                        }}
                                    >
                                        <Alert
                                            style={{
                                                marginBottom: 20,
                                            }}
                                            message="部分文件系统可能暂不支持在线预览，建议下载到本地"
                                            type="warning"
                                            showIcon
                                        />
                                        {previewData?.mimeType !== null &&
                                            previewData?.mimeType?.indexOf('image') > -1 ? (
                                            <Image width="100%" src={previewData?.url} />
                                        ) : (
                                            <Spin spinning={previewLoading}>
                                                <iframe
                                                    ref={iframeRef}
                                                    src={previewOnlineUrl}
                                                    height={200}
                                                    width="100%"
                                                    frameBorder="0"
                                                    // scrolling="false"
                                                    allowFullScreen={true}
                                                // scrolling={'no'}
                                                />
                                            </Spin>
                                        )}
                                    </DrawerForm>
                                </>
                            )}
                        </>
                    )}

                    {Array.isArray(details?.planList) && details?.planList.length === 0 && <ProCard title="报名信息" ghost>
                        <RegistrationInfo id={details.id} reload={reload} />
                    </ProCard>}

                    <div style={{ display: 'flex', paddingBlock: 20, flexDirection: 'column' }}>

                        <Card
                            bordered={false}
                            tabList={planItems}
                            style={{ width: '100%' }}
                            activeTabKey={planTab}
                            onTabChange={(key) => setPlanTab(key)}
                            tabProps={{
                                size: 'middle',
                                // tabPosition: 'left'
                            }}
                        />
                        {details?.planList.map((item) => {
                            //   {item.id===planTab&&}  
                            return item.id === planTab && <div style={{ display: 'flex', flexDirection: 'column' }}>
                                <Descriptions style={{ paddingInline: 10 }} column={1}>
                                    <Descriptions.Item label="带队人员">{item.leader}</Descriptions.Item>
                                    <Descriptions.Item label="联系电话">{item?.phone}</Descriptions.Item>
                                    <Descriptions.Item label="集中采访时间">{item?.travelTime}</Descriptions.Item>
                                    <Descriptions.Item label="采访地点">{item?.address}</Descriptions.Item>
                                    <Descriptions.Item label="发布会时间">{item?.presentationTime}</Descriptions.Item>
                                </Descriptions>
                                <Card
                                    bordered={false}
                                    tabList={[
                                        {
                                            tab: <span ><AudioOutlined style={{ marginRight: 5 }} />媒体信息</span>,
                                            key: 'media',
                                        },
                                        {
                                            tab: <span ><UserOutlined style={{ marginRight: 5 }} />采访对象</span>,
                                            key: 'organization',
                                        },
                                        {
                                            tab: <span ><CarOutlined style={{ marginRight: 5 }} />车辆安排</span>,
                                            key: 'cars',
                                        },
                                    ]}
                                    style={{ width: '100%' }}
                                    activeTabKey={tab}
                                    onTabChange={(key) => setTab(key)}
                                    tabProps={{
                                        size: 'middle',
                                    }}
                                />
                                {tab === 'cars' && <Card bordered title={<><CarOutlined style={{ marginRight: 5 }} />车辆安排</>} style={{ marginTop: -20, overflow: 'auto', maxHeight: '500px', scrollbarWidth: 'none' }}>
                                    {(Array.isArray(item?.carsList) && item?.carsList.length > 0) ? <Descriptions column={3}>
                                        {item?.carsList?.map((item) => <>
                                            <Descriptions.Item label="车牌号">
                                                {item?.number}
                                            </Descriptions.Item>
                                            <Descriptions.Item label="司机">
                                                {item?.name}
                                            </Descriptions.Item>
                                            <Descriptions.Item label="电话">
                                                {item?.phone}
                                            </Descriptions.Item>
                                        </>)}
                                    </Descriptions> : <></>}

                                </Card>}
                                {tab === 'media' && <div style={{ marginTop: -20, overflow: 'auto', maxHeight: '450px', scrollbarWidth: 'none' }}>
                                    {item?.mediaList?.map((item) =>
                                        <ProCard bordered headerBordered collapsible defaultCollapsed title={item?.mediaName} style={{ marginBottom: 10 }} >
                                            <Descriptions column={2}>
                                                {item.reporterList.map((item1) => <>
                                                    <Descriptions.Item label="记者">
                                                        {item1?.name}
                                                    </Descriptions.Item>
                                                    <Descriptions.Item label="电话">
                                                        {item1?.phone}
                                                    </Descriptions.Item></>
                                                )}
                                            </Descriptions>
                                        </ProCard>
                                    )}
                                    {/* {(Array.isArray(item?.mediaList) && item?.mediaList.length > 0) ? <></> : <Card bordered title={<><AudioOutlined style={{ marginRight: 5 }} />采访对象</>}><Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /></Card>} */}
                                </div>}
                                {tab === 'organization' && <div style={{ marginTop: -20, overflow: 'auto', maxHeight: '450px', scrollbarWidth: 'none' }}>
                                    {item?.assignOrganizationList?.map((item) =>
                                        <>
                                            <ProCard bordered headerBordered collapsible defaultCollapsed title={item?.organizationName} style={{ marginBottom: 10 }}>
                                                <Descriptions column={2} >
                                                    {item?.organizationList?.map((item) => <>
                                                        <Descriptions.Item label="联络人">
                                                            {item?.name}
                                                        </Descriptions.Item>
                                                        <Descriptions.Item label="电话">
                                                            {item?.phone}
                                                        </Descriptions.Item>

                                                    </>
                                                    )}

                                                </Descriptions>
                                                {item?.attachments && item?.attachments.length > 0 && <div style={{ marginBlock: 10 }}>
                                                    <span style={{ color: '#8c8c8c' }}>相关素材:</span>
                                                    <>
                                                        <Upload
                                                            listType="picture"
                                                            multiple
                                                            fileList={item?.attachments.map((item) => {
                                                                return {
                                                                    uid: item.id,
                                                                    name: item.name,
                                                                    url: item.content,
                                                                    mimeType: item.mimeType,
                                                                    status: 'done',
                                                                };
                                                            })}
                                                            showUploadList={{
                                                                downloadIcon: (
                                                                    <div style={{ marginLeft: '-100px', padding: '17px 0', marginTop: '-15px' }}>
                                                                        <DownloadOutlined
                                                                            style={{
                                                                                marginRight: '10px',
                                                                            }}
                                                                        />
                                                                        点击下载
                                                                    </div>
                                                                ),
                                                                showRemoveIcon: false,
                                                                showDownloadIcon: true,
                                                            }}
                                                            onPreview={async (file: UploadFile) => {
                                                                setPreviewData({
                                                                    id: file.uid,
                                                                    name: file.name,
                                                                    mimeType: file.mimeType,
                                                                    url: file.url,
                                                                });
                                                                setPreviewOpen(true);
                                                            }}
                                                        />
                                                        <DrawerForm
                                                            title={previewData?.name}
                                                            drawerProps={{
                                                                width: 900,
                                                                destroyOnClose: true,
                                                            }}
                                                            visible={previewOpen}
                                                            onVisibleChange={async (visible) => {
                                                                if (visible) {
                                                                    if (
                                                                        previewData?.mimeType !== null &&
                                                                        previewData?.mimeType?.indexOf('image') > -1
                                                                    ) {
                                                                        //图片预览
                                                                    } else {
                                                                        setPreviewLoading(true);

                                                                        // const response = await cuesAttachmentPreview({
                                                                        //     id: previewData?.id,
                                                                        // });

                                                                        // if (response.code === 0) {
                                                                        //     setPreviewOnlineUrl(response.data);
                                                                        // } else {
                                                                        //     message.error('暂时无法预览');
                                                                        //     setPreviewLoading(false);
                                                                        // }
                                                                    }
                                                                } else {
                                                                    setPreviewOpen(false);
                                                                    setPreviewData(undefined);
                                                                    setPreviewOnlineUrl(undefined);
                                                                }
                                                            }}
                                                            submitter={{
                                                                searchConfig: {
                                                                    submitText: '下载',
                                                                },
                                                            }}
                                                            onFinish={async (values) => {
                                                                window.open(previewData?.url, '_blank');
                                                            }}
                                                        >
                                                            <Alert
                                                                style={{
                                                                    marginBottom: 20,
                                                                }}
                                                                message="部分文件系统可能暂不支持在线预览，建议下载到本地"
                                                                type="warning"
                                                                showIcon
                                                            />
                                                            {previewData?.mimeType !== null &&
                                                                previewData?.mimeType?.indexOf('image') > -1 ? (
                                                                <Image width="100%" src={previewData?.url} />
                                                            ) : (
                                                                <Spin spinning={previewLoading}>
                                                                    <iframe
                                                                        ref={iframeRef}
                                                                        src={previewOnlineUrl}
                                                                        height={200}
                                                                        width="100%"
                                                                        frameBorder="0"
                                                                        // scrolling="false"
                                                                        allowFullScreen={true}
                                                                    // scrolling={'no'}
                                                                    />
                                                                </Spin>
                                                            )}
                                                        </DrawerForm>
                                                    </>
                                                </div>}
                                            </ProCard>
                                        </>
                                    )}
                                    {/* {(Array.isArray(item?.assignOrganizationList) && item?.assignOrganizationList.length > 0) ? <></> : <Card bordered title={<><UserOutlined style={{ marginRight: 5 }} />采访对象</>}><Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /></Card>} */}
                                </div>}
                            </div>
                        }
                        )}
                    </div>
                </Spin>

            </DrawerForm >
        </>
    );
};
export default DetailsInterview;